﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Milvus.Client;
using RagSharpCore.Service;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace RagSharpCore.WebApi.Controllers
{





	[Route("api/[controller]")]
	[ApiController]
	public class TestController : ControllerBase
	{



		[HttpGet("ConnectTest")]
		public async Task<IActionResult> ConnectTestTask()
		{
			string resp = "connected!";
			return Ok(new { resp });
		}


		[HttpGet("GetMilvusInfo")]
		public async Task<IActionResult> GetMilvusInfoTask()
		{
			Console.WriteLine("HelloWorld");
			// 在这里可以安全地使用 await
			string version = await MilvusOrm.instance.GetVersion();
			Console.WriteLine($"Milvus version: {version}");

			//cost_assistant_data
			var col_names = await MilvusOrm.instance.GetCollectionNames();
			var col_name_info = string.Join('\n', col_names);
			Console.WriteLine($"col_names:{col_name_info}");

			var collection = await MilvusOrm.instance.LoadCollection("price_assistant_data");
			var fields = await MilvusOrm.instance.GetCollectionFields();

			var fieldName = string.Join("\n", fields.Select(f => f.Name).ToList());
			Console.WriteLine($"fieldName:{fieldName}");

			var anonymousData = new
			{
				Code = 200,
				Message = "SUCCESS",
				Data = new
				{
					Version = version,
					CollectionNames = col_names,
					FieldName = fieldName,
				}
			};
			return Ok(anonymousData);
		}



		[HttpPost("TestEmbedding")]
		public async Task<IActionResult> TestEmbeddingTask(string prompt)
		{
			var collection = await MilvusOrm.instance.LoadCollection(collectionName: "price_assistant_data");
			// 使用 using 语句声明，确保对象使用后自动调用 Dispose 释放资源
			using var embedClient = new EmbeddingService();
			// 后续使用 embedClient 调用方法...
			var texts = new List<string> { prompt };
			var embeddings = await embedClient.GetEmbeddingsAsync(texts);
			var spare_embeddings = await embedClient.GetEmbeddingsAsync(texts, false);
			List<ReadOnlyMemory<float>> searchVectors =
				new List<ReadOnlyMemory<float>>() { embeddings![0].ToArray() };
			var outputFields = new List<string>() { "describ","name_property" };
			var responseData = await MilvusOrm.instance.SearchBy(
				 vectorFieldName: "describ_dense",
				 searchVectors: searchVectors,
				 expr: "",
				 outputFields: outputFields);

			var resDict =responseData.CastToDict();
			 
			return Ok(resDict);

			/* 
								 {
					  "collectionName": "price_assistant_data",
					  "fieldsData": [
						{
						  "fieldName": "describ",
						  "rowCount": 10,
						  "fieldId": 0,
						  "dataType": 21,
						  "isDynamic": false
						}
					  ],
					  "ids": {
						"longIds": [
						  459722454902359600,
						  459722454902358600,
						  459722454902359600,
						  459722454902359600,
						  459722454902359700,
						  459722454902359600,
						  459722454902369200,
						  459722454902359600,
						  459722454902361540,
						  459722454902361540
						],
						"stringIds": null
					  },
					  "numQueries": 1,
					  "scores": [
						0.6154,
						0.609,
						0.6078,
						0.6076,
						0.605,
						0.6041,
						0.6018,
						0.599,
						0.5987,
						0.5984
					  ],
					  "limit": 10,
					  "limits": [
						10
					  ]
					}
								*/
		}
		 
		[HttpPost("TestQwen")]
		public async Task<IActionResult> TestQwenTask(string prompt)
		{
			QwenService qwenService = new QwenService();

			var llmRes=await qwenService.RequestQwenAsync(prompt);
			  
			return Ok(new { llmRes }); 
		}


		 
		[HttpPost("RagDemo")]
		public async Task<IActionResult> RagDemoTask(string prompt)
		{ 
			var collection = await MilvusOrm.instance.LoadCollection(collectionName: "price_assistant_data");
			// 使用 using 语句声明，确保对象使用后自动调用 Dispose 释放资源
			using var embedClient = new EmbeddingService();
			// 后续使用 embedClient 调用方法...
			var texts = new List<string> { prompt };
			var embeddings = await embedClient.GetEmbeddingsAsync(texts);
			var spare_embeddings = await embedClient.GetEmbeddingsAsync(texts, false);
			List<ReadOnlyMemory<float>> searchVectors =
				new List<ReadOnlyMemory<float>>() { embeddings![0].ToArray() };
			//var outputFields = new List<string>() { "describ", "name_property" };
			var outputFields = new List<string>() {  "metadata" };
			var responseData = await MilvusOrm.instance.SearchBy(
				 vectorFieldName: "describ_dense",
				 searchVectors: searchVectors,
				 expr: "",
				 topK:5,
				 outputFields: outputFields);

			var resDict = responseData.CastToDict();

		 

			// 序列化配置：解决中文乱码
			var options = new JsonSerializerOptions
			{
				PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 驼峰命名
																   // 关键配置：允许中文等非ASCII字符直接输出（不转义）
				Encoder = JavaScriptEncoder.Create(
					UnicodeRanges.All   // 包含所有Unicode字符（包括中文）
					//new TextEncoderSettings()
				)
				// 简化写法（效果相同）：
				// Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
			};

			// 序列化（中文将正常显示）
			var referanceInfo = JsonSerializer.Serialize(resDict, options);

			prompt = $"这里有些参考:{referanceInfo}\n根据上述参考，请回答问题:{prompt}";

			QwenService qwenService = new QwenService(); 
			var llmRes=await qwenService.RequestQwenAsync(prompt); 
			return Ok(new { llmRes }); 
		}
		 


	}
}


